using System;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
using System.Linq;

namespace Core.Editor
{
    // 路径配置常量
    public static class InstallationPaths
    {
        public const string PackageName = "com.ly.hotcore";
        public const string PrefabSearchFilter = "t:Prefab";
    }

    // 在PrefabFinder类内增加候选类型定义
    public class PrefabCandidate
    {
        public string Path { get; set; }
        public GameObject Asset { get; set; }
    }

    // 预制体查找服务
    public static class PrefabFinder
    {
        public static GameObject FindEnginePrefab(string prefabName)
        {
            var candidates = AssetDatabase.FindAssets($"{InstallationPaths.PrefabSearchFilter} {prefabName}")
                .Select(AssetDatabase.GUIDToAssetPath)
                .Where(p => !string.IsNullOrEmpty(p))
                .Select(p => new PrefabCandidate
                {
                    Path = p,
                    Asset = AssetDatabase.LoadAssetAtPath<GameObject>(p)
                })
                .Where(x => x.Asset != null && x.Asset.name == prefabName)
                .ToList();

            return FindByPriority(candidates);
        }
        
        private static GameObject FindByPriority(List<PrefabCandidate> candidates)
        {
            return candidates.FirstOrDefault(x => PathChecker.IsInPackage(x.Path, InstallationPaths.PackageName))?.Asset
                   ?? candidates.FirstOrDefault()?.Asset;
        }
    }
    
    public static class PathChecker
    {
        public static bool IsInPackage(string path, string packageName)
        {
            return path.StartsWith($"Packages/{packageName}/") || path.Contains($"/{packageName}/");
        }
    }

    // 场景操作工具
    public static class SceneHelper
    {
        public static void PlaceAtSceneCenter(GameObject instance)
        {
            if (SceneView.lastActiveSceneView == null) return;

            instance.transform.position = SceneView.lastActiveSceneView.pivot;
            SceneView.FrameLastActiveSceneView();
            Selection.activeObject = instance;
            EditorGUIUtility.PingObject(instance);
        }
    }

    // 安装管理器
    public static class InstallationManager
    {
        private const string LauncherPrefabName = "Launcher";
        private const string DebugConsolePrefabName = "IngameDebugConsole";
        
        [MenuItem("HotCore/安装/安装启动器", priority = 1)]
        public static void InstallLauncherPrefab() => InstantiatePrefabAtCenter(LauncherPrefabName);

        [MenuItem("HotCore/安装/安装调试器", priority = 2)]
        public static void InstallDebugConsolePrefab() => InstantiatePrefabAtCenter(DebugConsolePrefabName);
        
        private static void InstantiatePrefabAtCenter(string targetPrefab)
        {
            var prefab = PrefabFinder.FindEnginePrefab(targetPrefab);
            if (prefab == null)
            {
                Debug.LogError($"Can't find {targetPrefab} prefab in resources");
                return;
            }

            try
            {
                var instance = PrefabUtility.InstantiatePrefab(prefab) as GameObject;
                if (instance == null)
                {
                    Debug.LogError($"Failed to instantiate {targetPrefab}");
                    return;
                }

                SceneHelper.PlaceAtSceneCenter(instance);
            }
            catch (Exception e)
            {
                Debug.LogError($"Error instantiating {targetPrefab}: {e.Message}");
            }
        }
    }
}